package Utils;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.util.Map;
import java.util.Set;

public class HbaseUtil {

    private Admin admin = null;
    private Connection conn = null;

    public void put(String tablename, String rowkey, String famliyname, Map<String,String> datamap) throws Exception {
        TableName tableName = TableName.valueOf(tablename);
        Table table = conn.getTable(TableName.valueOf(tablename));
        // 将字符串转换成byte[]
        byte[] rowkeybyte = Bytes.toBytes(rowkey);
        Put put = new Put(rowkeybyte);
        if (datamap != null) {
            Set<Map.Entry<String, String>> set = datamap.entrySet();
            for (Map.Entry<String, String> entry : set) {
                String key = entry.getKey();
                Object value = entry.getValue();
                put.addColumn(Bytes.toBytes(famliyname),Bytes.toBytes(key),Bytes.toBytes(value + ""));
            }
        }
        table.put(put);
        table.close();
        System.out.println("ok");
    }

    public String getdata(String tablename, String rowkey, String famliyname, String colum) throws Exception {
        Table table = conn.getTable(TableName.valueOf(tablename));
        // 将字符串转成byte[]
        byte[] rowkeybyte = Bytes.toBytes(rowkey);
        Get get = new Get(rowkeybyte);
        Result result = table.get(get);
        byte[] resultbytes = result.getValue(famliyname.getBytes(), colum.getBytes());
        if (resultbytes == null) {
            return null;
        }
        return new String(resultbytes);
    }

    // 插入数据
    public void putdata(String tablename, String rowkey, String famliyname, String colum, String data) throws Exception {
        Table table = conn.getTable(TableName.valueOf(tablename));
        Put put = new Put(rowkey.getBytes());
        put.addColumn(famliyname.getBytes(),colum.getBytes(),data.getBytes());
        table.put(put);
    }

    public HbaseUtil(Admin admin, Connection conn) {
        this.admin = admin;
        this.conn = conn;
    }

    public HbaseUtil() {
    }

}
